<?php

class Engine_Core_Form extends Zend_Form
{
	/**
	 * @var Engine_Core
	 */
	protected $_adapter;

	/**
	 * @return Engine_Core
	 */
	protected function getAdapter()
	{
		return $this->_adapter;
	}

	/**
	 * @return int
	 */
	public function save()
	{
		$values = $this->getValues();

		foreach($values as $id => $value) {
			$element = $this->getElement($id);

			if (!$value && ($element->getType() == 'Zend_Form_Element_File')) {
				unset($values[$id]);
			}
		}

		return $this->getAdapter()->saveEntry($values);
	}

	public function init()
	{
		$this->setName(get_class($this));
		$this->setMethod('post');
		$this->setEnctype('multipart/form-data');
	}

	public function populate($values)
	{
		parent::populate($values);

		foreach($this->getElements() as $element) {
			if ($element->getType() == 'Zend_Form_Element_File') {
				if ($src = $values[$element->getId()]) {
					$src = '/upload/' . $src;
					$name = $element->getId() . '_preview';
					$order = $element->getOrder() + 1;

					$this->addElement(new Engine_Form_Element_Image($name, array('order' => $order), array($name => $src)));
				}
			}
		}
	}
}